<template>
  <div v-loading="load">
    <el-row :gutter="6">
      <el-form
        ref="boxForm"
        :model="boxData"
        :rules="rules"
        size="mini"
        label-width="60px"
      >
        <el-card>
          <div slot="header" class="clearfix text-left">
            <el-col :span="23">
              <span class="title-icon">入库</span>
            </el-col>
            <el-col :span="1">
              <el-button size="mini" type="primary" @click="submitForm"
                >确定</el-button
              >
            </el-col>
          </div>
          <el-input size="mini" type="hidden" v-model="cur_orderNo"></el-input>
          <el-input size="mini" type="hidden" v-model="cur_isUps"></el-input>
          <el-row style="margin-top: 2px">
            <el-col :span="3">
              <el-form-item label="箱号" prop="boxNo">
                <el-input
                  v-model.trim="boxData.boxNo"
                  @keyup.enter.native="checkBoxNo"
                  placeholder="请输入箱号:运单号-数字 "
                  clearable
                  :style="{ width: '100%' }"
                  ref="ref_1"
                >
                </el-input>
              </el-form-item>
            </el-col>
            <el-col :span="4">
              <el-form-item prop="fbaBoxNo" label-width="120px">
                <div slot="label">
                  FBA箱号
                  <span class="text-sm text-blue" @click="forbidBox"
                    >({{ edit ? "启用" : "禁用" }})</span
                  >
                </div>
                <el-input
                  v-model="boxData.fbaBoxNo"
                  placeholder="请输入箱号运单号-FBA箱号"
                  @keyup.enter.native="checkBoxNo"
                  clearable
                  :disabled="edit"
                  :style="{ width: '100%' }"
                  ref="ref_2"
                >
                </el-input>
              </el-form-item>
            </el-col>
            <!-- <el-col :span="3">
               <el-form-item label="禁用" prop="delivery">
                 <el-switch v-model="boxData.delivery"></el-switch>
               </el-form-item>
             </el-col>-->
            <el-col :span="3">
              <el-form-item label="单箱重" prop="weight">
                <el-input
                  v-model="boxData.weight"
                  placeholder="请输入单箱重"
                  @keyup.enter.native="swithTab(5)"
                  clearable
                  :style="{ width: '100%' }"
                  ref="ref_3"
                >
                </el-input>
              </el-form-item>
            </el-col>
            <el-col :span="3">
              <el-form-item label="多箱重" prop="totalWeight">
                <el-input
                  v-model="boxData.totalWeight"
                  placeholder="请输入多箱重"
                  clearable
                  @keyup.enter.native="swithTab(5)"
                  :style="{ width: '100%' }"
                  ref="ref_4"
                >
                </el-input>
              </el-form-item>
            </el-col>
            <el-col :span="3">
              <el-form-item label="长" prop="length">
                <el-input
                  v-model="boxData.length"
                  placeholder="请输入长"
                  clearable
                  @keyup.enter.native="swithTab(6)"
                  :style="{ width: '100%' }"
                  ref="ref_5"
                >
                </el-input>
              </el-form-item>
            </el-col>
            <el-col :span="3">
              <el-form-item label="宽" prop="width">
                <el-input
                  v-model="boxData.width"
                  placeholder="请输入宽"
                  clearable
                  @keyup.enter.native="swithTab(7)"
                  :style="{ width: '100%' }"
                  ref="ref_6"
                >
                </el-input>
              </el-form-item>
            </el-col>
            <el-col :span="3">
              <el-form-item label="高" prop="height">
                <el-input
                  v-model="boxData.height"
                  placeholder="请输入高"
                  clearable
                  @keyup.enter.native="swithTab(8)"
                  :style="{ width: '100%' }"
                  ref="ref_7"
                >
                </el-input>
              </el-form-item>
            </el-col>
            <el-col :span="2">
              <el-form-item label="件数" prop="num">
                <el-input
                  v-model="boxData.num"
                  placeholder="请输入件数"
                  @keyup.enter.native="submitForm"
                  :step="1"
                  ref="ref_8"
                ></el-input>
              </el-form-item>
            </el-col>
          </el-row>
        </el-card>
        <el-card class="margin-top-sm">
          <span>仓库:</span>

          <el-select
            v-model="locationValue"
            placeholder="请选择"
            size="mini"
            class="margin-lr"
          >
            <el-option
              v-for="item in options"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            >
            </el-option>
          </el-select>

          <span class="margin-right-sm">关联库区</span>
          <el-input
            list="reservoir"
            v-model="boxData.reservoir"
            size="mini"
            name="reservoir"
            style="width:120px"
          ></el-input>

          <el-button
            v-if="info.length > 0"
            size="mini"
            @click="clickText(info[0], 0)"
            >{{ info[0] }}</el-button
          >
          <el-button
            v-if="info.length > 1"
            size="mini"
            @click="clickText(info[1], 1)"
            >{{ info[1] }}</el-button
          >
          <el-button
            v-if="info.length > 2"
            size="mini"
            @click="clickText(info[2], 2)"
            >{{ info[2] }}</el-button
          >
          <el-button
            class="margin-left"
            size="mini"
            type="primary"
            @click="synTemInfo"
            >同步临时数据</el-button
          >
          <el-button
            v-if="importButtonShow"
            class="margin-left"
            size="mini"
            type="primary"
            @click="importDialogShow=true"
          >导入入库信息</el-button>
        </el-card>

        <div model="result_id" v-if="showBoxResult">
          <el-card :span="15" class="margin-top">
            <div slot="header" class="clearfix text-left">
              <el-row class="text-sm">
                <el-col :span="2">
                  <span>客户:</span>
                  <span>{{ columns2.customerName }}</span>
                </el-col>
                <el-col :span="2">
                  <span>运单号:</span>
                  <span>{{ columns2.orderNo }}</span>
                </el-col>
                <el-col :span="2">
                  <span>件数:</span>
                  <span>{{ columns2.customerTotalPackages }}</span>
                </el-col>
                <el-col :span="2">
                  <span>重量:</span>
                  <span>{{ columns2.customerActualWeight }}</span>
                </el-col>
                <el-col :span="2">
                  <span>体积:</span>
                  <span>{{ columns2.customerVolume }}</span>
                </el-col>
                <el-col :span="2">
                  <span>计费重:</span>
                  <span>{{ columns2.customerChargedWeight }}</span>
                </el-col>
                <el-link type="primary">
                  <span
                    style="font-size: 15px; margin-left: 18px"
                    @click="toSyncCustomerData(this)"
                    >同步客户数据</span
                  >
                </el-link>
              </el-row>
            </div>
            <el-col :span="4" style="margin-top: 5px">
              <el-row style="margin-top: 5px">
                <span>目的国家:</span>
                <span>{{ columns2.countryName }}</span>
              </el-row>
              <el-row style="margin-top: 5px">
                <span>入库渠道:</span>
                <span>{{ columns2.inStockChannel }}</span>
              </el-row>
              <el-row style="margin-top: 5px">
                <span>客户备注:</span>
                <span>{{ columns2.customerRemark }}</span>
              </el-row>
              <el-row style="margin-top: 5px">
                <span>系统备注:</span>
              </el-row>
              <el-input
                type="textarea"
                placeholder="请输入备注内容"
                v-model="sysRemark"
                style="margin-top: 5px"
              ></el-input>
              <el-button
                type="primary"
                @click="updateRemark"
                size="mini"
                style="margin-top: 5px; float: middle; margin-left: 72%"
                >确定</el-button
              >
            </el-col>
            <el-col :span="20">
              <el-table
                :data="instockData"
                style="width: 100%"
                size="mini"
                show-summary
                :summary-method="getSummaries"
                border
              >
                <ex-table-column
                  type="index"
                  label="序号"
                  :auto-fit="true"
                  :fit-header="true"
                >
                </ex-table-column>
                <ex-table-column
                  property="boxNo"
                  label="箱号"
                  :auto-fit="true"
                  :fit-header="true"
                  width="200"
                >
                </ex-table-column>
                <ex-table-column
                  property="subWaybillNo"
                  label="子单号"
                  :auto-fit="true"
                  :fit-header="true"
                >
                </ex-table-column>
                <ex-table-column
                  property="weight"
                  label="实重"
                  :auto-fit="true"
                  :fit-header="true"
                >
                </ex-table-column>
                <ex-table-column
                  property="length"
                  label="长"
                  :auto-fit="true"
                  :fit-header="true"
                >
                </ex-table-column>
                <ex-table-column
                  property="width"
                  label="宽"
                  :auto-fit="true"
                  :fit-header="true"
                >
                </ex-table-column>
                <ex-table-column
                  property="height"
                  label="高"
                  :auto-fit="true"
                  :fit-header="true"
                >
                </ex-table-column>
                <ex-table-column
                  property="volume"
                  label="体积"
                  :auto-fit="true"
                  :fit-header="true"
                >
                </ex-table-column>
                <ex-table-column
                  property="volumeWeight"
                  label="体积重"
                  :auto-fit="true"
                  :fit-header="true"
                >
                </ex-table-column>
                <ex-table-column
                  property="chargeWeight"
                  label="计费重"
                  :auto-fit="true"
                  :fit-header="true"
                >
                </ex-table-column>
                <ex-table-column
                  label="操作"
                  width="150"
                  :auto-fit="true"
                  :fit-header="true"
                >
                  <template slot-scope="scope">
                    <el-button
                      size="mini"
                      type="danger"
                      @click="handleEdit(scope.row.id)"
                      slot="reference"
                      >编辑
                    </el-button>
                    <el-button
                      size="mini"
                      type="danger"
                      @click="
                        handleDelete(scope.row.id, scope.row, scope.$index)
                      "
                      >删除
                    </el-button>
                  </template>
                </ex-table-column>
              </el-table>
              <el-col :span="7">
                <span>.</span>
              </el-col>
              <el-col :span="2">
                <el-input
                  v-model="editTotalWeight"
                  placeholder="修改总实重"
                  size="mini"
                  clearable
                  @change="changeTotalWeight"
                >
                </el-input>
              </el-col>
              <el-button type="danger" size="mini" style="float: right">
                <span @click="handleBatchDelete(this)">批量删除</span>
              </el-button>
            </el-col>
            <!-- <el-col :span="5" style="margin-top: 5px">
               <el-table
                 :data="afterChargeData"
                 style="width: 100%; margin-left: 5%"
               >
                 <el-table-column prop="additional" label="附加费" width="100">
                 </el-table-column>
                 <el-table-column prop="remark" label="备注" width="170">
                 </el-table-column>
               </el-table>
             </el-col>-->
          </el-card>
        </div>

        <el-card style="margin-top: 5px">
          <el-form-item size="large">
            <el-button
              type="primary"
              @click="saveInstockInfo"
              style="float: center; margin-left: 40%"
              size="mini"
              :disabled="isDisable"
            >
              保存
            </el-button>
          </el-form-item>
        </el-card>
      </el-form>
    </el-row>

    <el-dialog title="入库临时数据" :visible.sync="boosyn">
      <el-table
        ref="multipleTable"
        :data="gridData"
        tooltip-effect="dark"
        style="width: 100%"
        max-height="650"
        @selection-change="handleSelectionChange"
      >
        <ex-table-column type="selection" width="30"> </ex-table-column>
        <ex-table-column prop="orderNo" label="运单号" width="160">
        </ex-table-column>
        <ex-table-column prop="customerName" label="客户" width="160">
        </ex-table-column>
        <ex-table-column
          prop="customerChannelName"
          label="入库渠道"
          width="160"
          show-overflow-tooltip
        >
        </ex-table-column>
        <ex-table-column
          prop="totalCount"
          label="总件数"
          width="80"
          show-overflow-tooltip
        >
        </ex-table-column>
        <ex-table-column
          prop="totalSize"
          width="80"
          label="临时数据件数"
          show-overflow-tooltip
        >
        </ex-table-column>
        <ex-table-column fixed="right" label="操作" width="80">
          <template slot-scope="scope">
            <el-button
              size="mini"
              type="danger"
              @click="
                handleSycDelete(scope.row.orderNo, scope.row, scope.$index)
              "
              >删除
            </el-button>
          </template>
        </ex-table-column>
      </el-table>
      <span slot="footer" class="dialog-footer">
        <el-button @click="boosyn = false">取消</el-button>
        <el-button type="primary" @click="saveSelectGoods">确定</el-button>
      </span>
    </el-dialog>

    <el-dialog title="批量导入入库信息" :visible.sync="importDialogShow">
      <el-upload
        class="upload-demo"
        drag
        :http-request="uploadFn"
        :show-file-list="false"
      >
        <i class="el-icon-upload"></i>
        <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
        <div class="el-upload__text">只能上传xlsx格式文件，请按模板要求录入数据，否则将上传失败</div>
      </el-upload>
      <a href="/static/download/入库导入模板.xlsx" download="入库导入模板.xlsx">点击下载Excel导入模板</a>
    </el-dialog>
    <div>
      <el-dialog title="编辑" :visible.sync="boopop">
        <el-form v-model="colValue" ref="basisForm" size="mini">
          <el-input size="mini" type="hidden" v-model="colValue.id"></el-input>
          <el-row>
            <el-col :span="10">
              <el-form-item label="订单号：" label-width="120px" prop="orderNo">
                <el-input
                  size="mini"
                  :disabled="true"
                  v-model="colValue.orderNo"
                ></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="10">
              <el-form-item label="箱号：" label-width="120px" prop="boxNo">
                <el-input
                  size="mini"
                  :disabled="true"
                  v-model="colValue.boxNo"
                ></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="10">
              <el-form-item label="重量：" label-width="120px" prop="weight">
                <el-input size="mini" v-model="colValue.weight"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="10">
              <el-form-item label="长：" label-width="120px" prop="length">
                <el-input size="mini" v-model="colValue.length"></el-input>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="10">
              <el-form-item label="宽：" label-width="120px" prop="width">
                <el-input size="mini" v-model="colValue.width"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="10">
              <el-form-item label="高：" label-width="120px" prop="height">
                <el-input size="mini" v-model="colValue.height"></el-input>
              </el-form-item>
            </el-col>
          </el-row>
          <el-col :span="2" style="float: right">
            <el-button size="mini" type="primary" @click="updateInstockInfo"
              >保存</el-button
            >
          </el-col>
        </el-form>
      </el-dialog>
    </div>
  </div>
</template>
<script>
import { ajax } from "@/store/yg/common/utils";
import axios from "axios";
import * as constant from "@/store/yg/common/constant";
import { untransform } from "@/store/yg/common/uri";

export default {
  components: {},
  props: [],
  data() {
    return {
      load: false,
      action: "",
      importDialogShow: false,
      importButtonShow: true,
      boxData: {
        boxNo: "",
        fbaBoxNo: "",
        weight: "",
        totalWeight: "",
        length: "",
        width: "",
        height: "",
        num: 1,
        orderNo: "",
        reservoir: ""
      },
      colValue: {
        id: "",
        orderNo: "",
        boxNo: "",
        weight: "",
        length: "",
        width: "",
        height: ""
      },
      sysRemark: "",
      arr: [],
      info: [],
      boosyn: false,
      showBoxResult: false,
      gridData: [],
      options: [],
      locationValue: "",
      afterChargeData: [],
      totalWeight: "",
      totalVolume: "",
      totalChargeWeight: "",
      waybillNo: "",
      edit: false,
      boopop: false,
      isDisable: false,
      columns2: [],
      instockData: [],
      totalVolume: "",
      totalWeight: "",
      volumeWeight: "",
      upsChargeWeight: "",
      finalChargeWeight: "",
      chargedWeightErrorRange: "",
      chargingMode: "",
      cu: {},
      cur_orderNo: "",
      cur_isUps: "",
      editTotalWeight: '',
      rules: {
        boxNo: [],
        fbaBoxNo: [],
        weight: [],
        totalWeight: [],
        length: [
          {
            required: true,
            message: "请输入正数长",
            trigger: "blur",
            validator: this.isDecimali
          }
        ],
        width: [
          {
            required: true,
            message: "请输入正数宽",
            trigger: "blur",
            validator: this.isDecimali
          }
        ],
        height: [
          {
            required: true,
            message: "请输入正数高",
            trigger: "blur",
            validator: this.isDecimali
          }
        ],
        num: [
          {
            required: true,
            message: "请输入正整数件数",
            trigger: "blur",
            validator: this.isInteger
          }
        ]
      }
    };
  },
  computed: {},

  watch: {},

  created: function() {
    this.action =
      constant.API_SERVER +
      "/api/consume/upload?uri=" +
      untransform(this.$route.params.uri) +
      "&f=importInstockData&type=blank"
  },

  mounted() {
    this.storageLocations();
    if (JSON.parse(sessionStorage.getItem("reservoir"))) {
      this.info = JSON.parse(sessionStorage.getItem("reservoir"));
      // console.log("this.info: ", this.info);
    }
  },
  methods: {
    clickText(num, index) {
      if (index === 0) {
        this.boxData.reservoir = num;
      } else if (index === 1) {
        this.boxData.reservoir = num;
      } else if (index === 2) {
        this.boxData.reservoir = num;
      }
    },
    submitForm() {
      if (this.boxData.weight === "" && this.boxData.totalWeight === "") {
        return this.$message.error("单箱重或多箱重不能为空");
      }
      if (this.boxData.weight && this.boxData.totalWeight) {
        this.$message.error("单箱重与多箱重不能同时填");
        return;
      }
      this.waybillNo = this.$refs["boxForm"].validate(valid => {
        if (!valid) return;
        this.boxData.orderNo = this.cur_orderNo;
        ajax("addInstockGoods", this.boxData).then(
          res => {
            console.log(res);
            if (res.code != 200) {
              this.$message.error("获取失败，" + res.message);
            } else {
              this.$message.success("保存信息成功");
              this.instockData = this.instockData.concat(res.data);
              this.cu = this.instockData[0];
              this.$refs.ref_1.focus();
              //this.boxData.boxNo = "";
              this.tatalCarcar(this.instockData);
            }
          },
          error => {
            console.log(error);
          }
        );
      });
    },
    tatalCarcar(obj) {
      var totalWeight = 0;
      var totalVolume = 0;
      var totalVolumeWeight = 0;
      var upsChargeWeight = 0;
      for (var str of obj) {
        if (str.weight) {
          totalWeight += parseFloat(str.weight);
        }
        if (str.length && str.width && str.height) {
          totalVolume +=
            parseFloat(str.length) *
            parseFloat(str.width) *
            parseFloat(str.height);
        }

        if (str.volumeWeight) {
          totalVolumeWeight += parseFloat(str.volumeWeight);
        }
        if (str.chargeWeight) {
          upsChargeWeight += parseFloat(str.chargeWeight);
        }
      }
      this.totalVolume = Math.round((totalVolume / 1000000) * 1000) / 1000;
      this.totalWeight = Math.round(totalWeight * 100) / 100;
      if (totalVolumeWeight != 0) {
        totalVolumeWeight = Math.round(totalVolumeWeight * 100) / 100;
        this.volumeWeight = totalVolumeWeight;
        var finalChargeWeight = 0;
        if (upsChargeWeight > 0) {
          finalChargeWeight = upsChargeWeight;
        } else {
          finalChargeWeight =
            totalWeight > totalVolumeWeight ? totalWeight : totalVolumeWeight;
        }
        this.chargeWeight = this.carry(finalChargeWeight);
      } else {
        this.chargeWeight = 0;
        this.volumeWeight = 0;
      }
    },
    carry(d) {
      var floor = Math.floor(d);
      var decimals = d - floor;
      if (decimals < 0.1) {
        return floor;
      }
      var result = 0.5;
      if (d == 0) {
        return result;
      }
      var x = parseInt(d);
      var y = d - x;
      if (y == 0) {
        return d;
      }
      if (d > 21) {
        //大货
        result = Math.ceil(d);
      } else {
        var param = y + 0.5;
        if (param > 1) {
          result = Math.ceil(d);
        } else {
          result = Math.ceil(d) - 0.5;
        }
      }
      return result;
    },
    swithTab(i) {
      if (i == 4) {
        this.boxData.totalWeight = "";
        this.$refs.ref_4.focus();
      } else if (i == 5) {
        this.boxData.length = "";
        this.$refs.ref_5.focus();
      } else if (i == 6) {
        this.boxData.width = "";
        this.$refs.ref_6.focus();
      } else if (i == 7) {
        this.boxData.height = "";
        this.$refs.ref_7.focus();
      } else if (i == 8) {
        this.boxData.num = "";
        this.$refs.ref_8.focus();
      }
    },
    resetForm() {
      this.$refs["boxForm"].resetFields();
    },
    handleEdit(id) {
      ajax("findbyid", { id: id }).then(
        res => {
          console.log(res);
          this.colValue = res;
          this.boopop = true;
        },
        error => {
          console.log(error);
        }
      );
    },
    handleDelete(id, row, i) {
      ajax("delete", { id: id }).then(
        res => {
          console.log(res);
          if (res.code == 200) {
            this.$message.success("删除成功");
            this.instockData.splice(i, 1);
            this.tatalCarcar(this.instockData);
          } else {
            this.$message.error("获取失败，" + res.message);
          }
        },
        error => {
          console.log(error);
        }
      );
    },
    handleBatchDelete() {
      if (!this.instockData || this.instockData.length == 0) {
        this.$message.error("当前无数据可删除");
        return;
      }
      var ids = "";
      for (var i in this.instockData) {
        if (ids == "") {
          ids = this.instockData[i].id;
        } else {
          ids += "," + this.instockData[i].id;
        }
      }
      ajax("batchDeleteInstockGoods", { ids: ids }).then(
        res => {
          console.log(res);
          if (res.code == 200) {
            this.$message.success("删除成功");
            this.instockData = [];
          } else {
            this.$message.error("获取失败，" + res.message);
          }
        },
        error => {
          console.log(error);
        }
      );
    },
    getSummaries(param) {
      const { columns, data } = param;
      const sums = [];
      columns.forEach((column, index) => {
        if (index === 0) {
          sums[index] = "合计";
          return;
        }
        sums[3] = this.totalWeight;
        sums[7] = this.totalVolume;
        sums[8] = this.volumeWeight;
        sums[9] = this.chargeWeight;
      });

      return sums;
    },
    updateRemark() {
      ajax("updateRemark", {
        sysRemark: this.sysRemark,
        orderNo: this.columns2.orderNo
      }).then(
        res => {
          console.log(res);
          if (res.code != 200) {
            this.$message.error("添加系统备注失败" + res.message);
          } else {
            this.$message.success("添加系统备注成功");
          }
        },
        error => {
          console.log(error);
        }
      );
    },
    checkBoxNo() {
      this.showBoxResult = true;
      var param = "";
      if (!this.boxData.boxNo && this.boxData.fbaBoxNo) {
        param = this.boxData.fbaBoxNo;
      } else if (this.boxData.boxNo && !this.boxData.fbaBoxNo) {
        param = this.boxData.boxNo;
      }
      ajax("checkBoxNo", { boxNo: param }).then(
        res => {
          console.log(res);
          if (res.code != 200) {
            this.$message.error("箱号不存在" + res.message);
          } else {
            this.$message.success("请求成功");
            //this.columns = res.data;
            this.cur_orderNo = res.data.orderNo;
            this.cur_isUps = res.data.isUps;
            this.waybillId = res.data.waybillId;
            this.chargedWeightErrorRange = res.data.chargedWeightErrorRange;
            this.chargingMode = res.data.chargingMode;
            this.$refs.ref_3.focus();
            this.columns2 = res.data2;
            this.columns2.orderNo = res.data2.waybillNo;
            this.columns2.customerName = res.data3;
            this.columns2.inStockChannel = res.data4;
            //隐藏导入按钮
            this.importButtonShow = false;
          }
        },
        error => {
          console.log(error);
        }
      );
    },
    handleSelectionChange(val) {
      this.multipleSelection = val;
    },
    synTemInfo() {
      ajax("synTemInstockInfo", {}).then(
        res => {
          console.log(res);
          if (res.code == 200) {
            this.gridData = res.data;
            this.boosyn = true;
          } else {
            this.$message.error("操作失败，" + res.message);
          }
        },
        error => {
          console.log(error);
        }
      );
    },
    storageLocations: function() {
      ajax("storageLocations", {}).then(
        res => {
          console.log(res);
          if (res.code == 200) {
            this.options = res.data2;
            this.locationValue = res.data;
          } else {
            this.$message.error("操作失败，" + res.message);
          }
        },
        error => {
          console.log(error);
        }
      );
    },
    forbidBox() {
      if (this.edit) {
        this.edit = false;
      } else {
        this.edit = true;
      }
    },
    isDecimali(rule, value, callback) {
      if (!value) {
        return callback(new Error("输入不可以为空"));
      }
      setTimeout(() => {
        if (!Number(value)) {
          callback(new Error("请输入[1,100]之间的数字"));
        } else {
          if (value < 0 || value > 100000000) {
            callback(new Error("请输入[1,100]之间的数字"));
          } else {
            callback();
          }
        }
      }, 100);
    },
    isInteger(rule, value, callback) {
      console.log("value", value);
      if (!value) {
        return callback(new Error("输入不可以为空"));
      }
      setTimeout(() => {
        if (!Number(value)) {
          callback(new Error("请输入正整数"));
        } else {
          const re = /^[0-9]*[1-9][0-9]*$/;
          const rsCheck = re.test(value);
          if (!rsCheck) {
            callback(new Error("请输入正整数"));
          } else {
            callback();
          }
        }
      }, 0);
    },
    updateInstockInfo() {
      console.log(this.colValue);
      ajax("save", this.colValue).then(
        res => {
          console.log(res);
          if (res.code != 200) {
            this.$message.error("修改信息失败" + res.message);
          } else {
            this.boopop = false;
            this.calInstockData();
            console.log(this.instockData);
          }
          this.boopop = false;
        },
        error => {
          console.log(error);
        }
      );
    },
    calInstockData() {
      ajax("calInstockData", this.colValue).then(
        res => {
          console.log(res);
          if (res.code != 200) {
            this.$message.error("修改信息失败" + res.message);
          } else {
            this.$message.success("修改信息成功");
            console.log(this.instockData.length);
            for (var i = 0; i < this.instockData.length; i++) {
              if (this.instockData[i].id === this.colValue.id) {
                Object.assign(this.instockData[i], res.data);
                //this.$set(this.columns[i],'','')
              }
            }
            this.tatalCarcar(this.instockData);
          }
        },
        error => {
          console.log(error);
        }
      );
    },
    handleSycDelete(orderNo, row, i) {
      ajax("sycDelete", { orderNo: orderNo }).then(
        res => {
          console.log(res);
          if (res.code == 200) {
            this.$message.success("删除成功");
            this.gridData.splice(i, 1);
            this.tatalCarcar(this.instockData);
          } else {
            this.$message.error("操作失败，" + res.message);
          }
        },
        error => {
          console.log(error);
        }
      );
    },
    saveSelectGoods() {
      if (this.multipleSelection.length > 1) {
        this.$message.error("暂时只能单选");
        return;
      }
      ajax("queryInstockGoodsByOrderNos", this.multipleSelection).then(
        res => {
          console.log(res);
          if (res.code == 200) {
            this.boosyn = false;
            this.showBoxResult = true;
            this.instockData = res.data;
            this.columns2 = res.data2;
            this.tatalCarcar(this.instockData);
          } else {
            this.$message.error("保存失败" + res.message);
          }
        },
        error => {
          console.log(error);
        }
      );
    },
    handleMessSycDelete(obj) {
      ajax("handleMessSycDelete", this.multipleSelection).then(
        res => {
          console.log(res);
          if (res.code == 200) {
            this.$message.success("保存成功");
            this.boosyn = false;
          } else {
            this.$message.error("保存失败" + res.message);
          }
        },
        error => {
          console.log(error);
        }
      );
    },
    toSyncCustomerData(obj) {
      var waybillId = this.waybillId;
      if (!waybillId) {
        this.$message.error("运单信息获取失败");
        return;
      }
      if (this.instockData) {
        this.$confirm("自动获取会覆盖原有数据，是否确认获取？", "提示", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(() => {
          this.syncCustomerData(waybillId, this.instockData);
        });
      } else {
        this.syncCustomerData(waybillId, this.instockData);
      }
    },
    syncCustomerData(waybillId, instockData) {
      ajax("synCustomerPackData", { orderId: waybillId }).then(
        res => {
          console.log(res);
          if (res.code == 200) {
            this.instockData = res.data;
            this.tatalCarcar(this.instockData);
            this.$message.success("保存成功");
          } else {
            this.$message.error("保存失败" + res.message);
          }
        },
        error => {
          console.log(error);
        }
      );
    },
    checkChargedWeightErrorRange(chargingMode, chargedWeightErrorRange) {
      var tips = "";
      if (!chargedWeightErrorRange) {
        chargedWeightErrorRange = 0;
      }
      var firstData = 0;
      var endData = 0;
      var chargingModeTip = "";
      if (chargingMode == 1) {
        firstData = this.columns2.customerVolume;
        endData = this.totalVolume;
        chargingModeTip = "体积";
      } else if (chargingMode == 2) {
        firstData = this.columns2.customerChargedWeight;
        endData = this.chargeWeight;
        chargingModeTip = "计费重";
      } else {
        firstData = this.columns2.customerActualWeight;
        endData = this.totalWeight;
        chargingModeTip = "实重";
      }
      if (!firstData) {
        tips +=
          "计费异常：当前订单->客户" +
          chargingModeTip +
          "：0 九方" +
          chargingModeTip +
          "：" +
          endData +
          " 误差[无穷大]超过误差范围" +
          chargedWeightErrorRange;
      }
      if (!endData) {
        endData = 0;
      }
      var diffWeight = Math.abs(firstData - endData);
      var actualErrorRange = diffWeight / firstData;
      actualErrorRange = Math.round(actualErrorRange * 10000) / 10000;
      if (actualErrorRange > chargedWeightErrorRange) {
        tips +=
          "计费异常：当前订单->客户" +
          chargingModeTip +
          "：" +
          firstData +
          " 九方" +
          chargingModeTip +
          "：" +
          endData +
          " 误差" +
          actualErrorRange +
          "超过误差范围" +
          chargedWeightErrorRange;
      }
      return tips;
    },
    changeTotalWeight(){
      if (!this.editTotalWeight){
        return;
      }
      var sigleWeight = (this.editTotalWeight/this.instockData.length).toFixed(2);
      for (var i of this.instockData){
        i.weight =sigleWeight;
      }
      this.tatalCarcar(this.instockData);
    },
    saveInstockInfo() {
      this.isDisable = true;
      if (JSON.parse(sessionStorage.getItem("reservoir"))) {
        this.arr = JSON.parse(sessionStorage.getItem("reservoir"));
        this.arr.unshift(this.boxData.reservoir);
      } else {
        this.arr.unshift(this.boxData.reservoir);
      }
      sessionStorage.setItem("reservoir", JSON.stringify(this.arr));
      if (
        this.instockData.length != this.columns2.customerTotalPackages ||
        this.totalVolume != this.columns2.customerVolume ||
        this.totalWeight != this.columns2.customerActualWeight ||
        this.chargeWeight != this.columns2.customerChargedWeight
      ) {
        var tips = "";
        const confirmText = [];
        if (this.instockData.length != this.columns2.customerTotalPackages) {
          tips =
            this.cur_orderNo +
            "：件数异常，客户预报件数" +
            this.columns2.customerTotalPackages +
            "件，实际入库件数" +
            this.instockData.length +
            ";";
          confirmText.push(tips);
        }
        if (this.totalWeight != this.columns2.customerActualWeight) {
          var chargedWeightErrorRangeTips = this.checkChargedWeightErrorRange(
            0,
            this.chargedWeightErrorRange
          );
          // tips += this.cur_orderNo + chargedWeightErrorRangeTips + ";";
          confirmText.push(this.cur_orderNo + chargedWeightErrorRangeTips);
        }
        if (this.totalVolume != this.columns2.customerVolume) {
          var chargedWeightErrorRangeTips = this.checkChargedWeightErrorRange(
            1,
            this.chargedWeightErrorRange
          );
          // tips += this.cur_orderNo + chargedWeightErrorRangeTips + ";";
          confirmText.push(this.cur_orderNo + chargedWeightErrorRangeTips);
        }
        if (this.chargeWeight != this.columns2.customerChargedWeight) {
          var chargedWeightErrorRangeTips = this.checkChargedWeightErrorRange(
            2,
            this.chargedWeightErrorRange
          );
          // tips += this.cur_orderNo + chargedWeightErrorRangeTips + ";";
          confirmText.push(this.cur_orderNo + chargedWeightErrorRangeTips);
        }

        this.$confirm(
          `<p style='color:#f56c6c'>${confirmText[0]}</p>
           <p style='color:#67C23A'>${confirmText[1]}</p>
           <p style='color:#E6A23C'>${confirmText[2]}</p>
           `,
          {
            dangerouslyUseHTMLString: true
          }
        )
          .then(_ => {
            this.saveInstockInfoAction();
          })
          .catch(_ => {
            this.isDisable = false;
          });
      } else {
        this.saveInstockInfoAction();
      }
    },
    saveInstockInfoAction() {
      var cur = {};
      this.load = true;
      cur["orderNo"] = this.cur_orderNo;
      cur["goodsList"] = this.instockData;
      cur["storageLocation"] = this.locationValue;
      cur["reservoirArea"] = this.boxData.reservoir;
      console.log(cur);
      // 关联库区
      // cur["reservoir"] = this.boxData.reservoir;
      let attrs = {};
      attrs["headers"] = {
        "YG-UNIQUE-KEY": "save_instock_info_" + new Date().getTime()
      };
      ajax("saveInstockInfo", cur, attrs).then(
        res => {
          console.log(res);
          if (res.code == 200) {
            if (res.message) {
              this.$message.success(res.message);
            } else {
              this.$message.success("保存成功！");
            }
            // this.timeout = setTimeout(() => {
            //   window.location.reload(true);
            // }, 3000 * Math.random());
            setTimeout(() => {
              location.reload();
            }, 2000);
          } else {
            this.$message.error("保存错误:" + res.message);
            this.isDisable = false;
          }
          this.load = false;
        },
        error => {
          console.log(error);
          this.load = false;
          this.isDisable = false;
        }
      );
    },

    /**
     * 根据excel导入文件组装入库数据
     * */
    uploadFn(params) {
      const file = params.file;
      let fileName = file.name;
      //校验是否为xlsx
      if (fileName.indexOf('.') > -1) {
        let suffix = fileName.substr(fileName.lastIndexOf(".") + 1);
        if (suffix != 'xlsx') {
          this.$message.error("只能上传xlsx格式文件");
          return;
        }
      }
      const form = new FormData();
      form.append("items[]", file);
      //打开遮罩层
      this.load = true;
      axios({
        method: "post",
        url: this.action,
        data: form
      })
        .then(response => {
          if (response.data.code === 200) {
            this.importDialogShow = false;
            this.importButtonShow = false;
            this.showBoxResult = true;
            this.instockData = response.data.data;
            this.columns2 = response.data.data2;
            this.cur_orderNo = this.columns2.orderNo;
            this.tatalCarcar(this.instockData);
          } else {
            if (response.data.message) {
              this.$message.error("导入失败:" + response.data.message);
            }
          }
          this.load = false;
        })
        .catch(error => {
          this.$message.error("导入失败:" + error);
        });
    }
  }
};
</script>
<style></style>
